//
//  ClubSquareDatailView.swift
//  77Club
//
//  Created by Apple on 2024/9/5.
//

import UIKit

class ClubSquareDatailNavView: UIView, RaeNetworkProtocol {
    
    private let backButton = c_make_ex(UIButton.self)
        .image("Common_whiteBack").end()
    private let moreButton = c_make_ex(UIButton.self)
        .image("Square_detail_more").end()
    private let searchButton = c_make_ex(UIButton.self)
        .image("Square_detail_search").end()
    private let managerButton = c_make_ex(UIButton.self)
        .image("Square_detail_manager").end()
    private let bgImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
    private let shadowView = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.45)).end()
    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(12.0.Scale).border(.white.alpha(0.1), width: 1)
        .mode(.scaleAspectFill).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color(.white).font(16.font_semiBold).end()
    private let joinLabel = c_make_ex(UILabel.self)
        .color(.white.alpha(0.8))
        .font(10.font_medium).end()
    private let infoLabel = c_make_ex(UILabel.self)
        .color(.white.alpha(0.9)).font(11.font_medium).corner(4)
        .bgColor(.white.alpha(0.4)).alignment(.center).end()
    private let noticeLabel = c_make_ex(UILabel.self)
        .color(.white).font(12.font_medium).end()
    private var joinButton = c_make_ex(UIButton.self)
        .image("Square_detail_attention").image("Square_detail_attentioned", state: .selected).end()
    private var topIconImageV = c_make_ex(UIImageView.self)
        .corner(8.0.Scale).border(.white.alpha(0.1), width: 1)
        .mode(.scaleAspectFill).end()
    private var topNameLabel = c_make_ex(UILabel.self)
        .color(.white).font(16.font_semiBold).end()
    private var topJoinButton = c_make_ex(UIButton.self)
        .image("Square_detail_attention").image("Square_detail_attentioned", state: .selected).end()
    
    var communityId: String = ""
    var model: ClubGameCommunityModel? {
        didSet{
            guard let md = model else { return }
            
            bgImageView.loadImage(url: md.bgimg)
            iconImageView.loadImage(url: md.icon)
            nameLabel.text = md.name
            let guanzhu = ClubGlobalTool.shared.formatNumber(num: "\(md.guanzhu_num)")
            var joinString = ""
            if md.settings == "" || md.settings == "未设置" {
                joinString = guanzhu + "人关注"
            }else{
                joinString = md.settings.replacingOccurrences(of: "#", with: guanzhu)
            }
            joinString = ClubGlobalTool.shared.formatNumber(num: "\(md.bbs_num)") + "篇帖子 · " + joinString
            joinLabel.text = joinString
            infoLabel.text = "论坛介绍"
            noticeLabel.text = "公告：" + md.notice
            joinButton.isSelected = md.is_guanzhu
            topJoinButton.isSelected = md.is_guanzhu
            topIconImageV.loadImage(url: md.icon)
            topNameLabel.text = md.name
            if md.my_role == 1 || md.my_role == 2 {
                managerButton.isHidden = false
                managerButton.widthConstraint?.constant = 32
                topJoinButton.widthConstraint?.constant = 0
                topJoinButton.isHidden = true
                joinButton.isHidden = true
            }else{
                managerButton.isHidden = true
                managerButton.widthConstraint?.constant = 0
                topJoinButton.widthConstraint?.constant = 80.0.Scale
                topJoinButton.isHidden = false
                joinButton.isHidden = false
            }
        }
    }
    
    var topViewAlpha: CGFloat = 0.0 {
        didSet{
            topIconImageV.alpha = topViewAlpha
            topNameLabel.alpha = topViewAlpha
            topJoinButton.alpha = topViewAlpha
        }
    }
    
    var backBlock: (() -> Void)?
    var moreBlock: (() -> Void)?
    var searchBlock: (() -> Void)?
    var toManagerVCBlock: (() -> Void)?
    var joinBlock: ((_ isJoined: Bool, _ md: ClubGameCommunityModel) -> Void)?
    var toNoticeVC: (() -> Void)?
    var toInfoVC: (() -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
     
        clipsToBounds = true
        
        subviews{
            bgImageView.subviews{
                shadowView
            }
            backButton
            moreButton
            searchButton
            managerButton
            iconImageView
            nameLabel
            joinLabel
            infoLabel
            noticeLabel
            joinButton
            topIconImageV
            topNameLabel
            topJoinButton
        }
        
        bgImageView.fillContainer()
        shadowView.fillContainer()
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        moreButton.trailing(0).top(.statusHeight).width(47).height(44)
        managerButton.trailing(47).top(.statusHeight + 6).size(32)
        searchButton.top(.statusHeight + 6).size(32)
        searchButton.Trailing == managerButton.Leading
        iconImageView.leading(12.0.Scale).size(60.0.Scale)
        iconImageView.Top == backButton.Bottom + 15.0.Scale
        nameLabel.leading(80.0.Scale).trailing(88.0.Scale)
        nameLabel.Top == iconImageView.Top + 2.0.Scale
        joinLabel.leading(80.0.Scale).trailing(88.0.Scale)
        joinLabel.CenterY == iconImageView.CenterY
        infoLabel.leading(80.0.Scale).width(60.0.Scale).height(18.0.Scale)
        infoLabel.Top == joinLabel.Bottom + 5
        noticeLabel.leading(12.0.Scale).trailing(12.0.Scale)
        noticeLabel.Top == iconImageView.Bottom + 8.0.Scale
        joinButton.trailing(12.0.Scale).width(80.0.Scale).height(30.0.Scale)
        joinButton.CenterY == iconImageView.CenterY
        topIconImageV.leading(56).size(32)
        topIconImageV.CenterY == backButton.CenterY
        topNameLabel.leading(100)
        topNameLabel.CenterY == topIconImageV.CenterY
        topNameLabel.Trailing == topJoinButton.Leading - 5.0.Scale
        topJoinButton.width(80.0.Scale).height(30.0.Scale)
        topJoinButton.CenterY == topNameLabel.CenterY
        topJoinButton.Trailing == searchButton.Leading - 5.0.Scale
        
        topIconImageV.alpha = 0
        topNameLabel.alpha = 0
        topJoinButton.alpha = 0
        
        let noticeTap = UITapGestureRecognizer(target: self, action: #selector(clickNoticeLabel))
        noticeLabel.isUserInteractionEnabled = true
        noticeLabel.addGestureRecognizer(noticeTap)
        let infoTap = UITapGestureRecognizer(target: self, action: #selector(clickInfoLabel))
        infoLabel.isUserInteractionEnabled = true
        infoLabel.addGestureRecognizer(infoTap)
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        managerButton.addTarget(self, action: #selector(clickSettingButton), for: .touchUpInside)
        moreButton.addTarget(self, action: #selector(clickMoreButton), for: .touchUpInside)
        searchButton.addTarget(self, action: #selector(clickSearchButton), for: .touchUpInside)
        joinButton.addTarget(self, action: #selector(clickJoinButton), for: .touchUpInside)
        topJoinButton.addTarget(self, action: #selector(clickJoinButton), for: .touchUpInside)
    }
    
    @objc private func clickInfoLabel(){
        toInfoVC?()
    }
        
    @objc private func clickNoticeLabel(){
        toNoticeVC?()
    }
    
    @objc private func clickBackButton(){
        backBlock?()
    }
    
    @objc private func clickSettingButton(){
        toManagerVCBlock?()
    }
    
    @objc private func clickMoreButton(){
        moreBlock?()
    }
    
    @objc private func clickSearchButton(){
        searchBlock?()
    }
    
    @objc private func clickJoinButton(){
        
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            if joinButton.isSelected {
                Task{
                    let res = await network.request(.cancelCollectGoods(goodsId: model?.shoucang_id ?? "", type: "0"),isShowError: false)
                    if res.isSuccess {
                        joinButton.isSelected = false
                        topJoinButton.isSelected = false
                        guard let md = model else { return }
                        self.joinBlock?(self.joinButton.isSelected,md)
                    }
                }
            }else{
                Task{
                    let res = await network.request(.collectGoods(goodsId: communityId, type: "0"),isShowError: false)
                    if res.isSuccess {
                        joinButton.isSelected = true
                        topJoinButton.isSelected = true
                        guard let md = model else { return }
                        self.joinBlock?(self.joinButton.isSelected,md)
                    }
                }
            }
        }else{
            UIApplication.topController()?.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


class ClubSquareDatailCateView: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    
    var models: [ClubGameCommunityFenLeiModel]? {
        didSet{
            collectionView.reloadData()
        }
    }
    
    var updateDetailListView: ((_ type: String) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = "#E8E9EB".toColor
        
        subviews{
            collectionView
        }
        
        collectionView.leading(0).trailing(0).top(12.0.Scale).height(32.0.Scale)
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        layout.sectionInset = UIEdgeInsets(top: 0, left: 8.0.Scale, bottom: 0, right: 0)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(ClubSquareDatailCateCell.self, forCellWithReuseIdentifier: ClubSquareDatailCateCell.description())
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return models?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubSquareDatailCateCell.description(), for: indexPath) as? ClubSquareDatailCateCell else { return UICollectionViewCell() }
        cell.model = models?[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        var temp = [ClubGameCommunityFenLeiModel]()
        models?.forEach { model in
            var itemModel = model
            itemModel.isSel = false
            temp.append(itemModel)
        }
        temp[indexPath.row].isSel = true
        models = temp
        updateDetailListView?(temp[indexPath.row].type)
        
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let name = models?[indexPath.row].name ?? ""
        let font = 12.font_semiBold
        let attributedText = NSAttributedString(string: name, attributes: [NSAttributedString.Key.font: font as Any])

        // 计算文本宽度
        let size = attributedText.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil).size
        let width = size.width + 24.0.Scale
        
        return CGSize(width: width, height: 24.0.Scale)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: 社区分类cell
class ClubSquareDatailCateCell: UICollectionViewCell {
    
    private let cateButton = c_make_ex(UIButton.self)
        .corner(12).color("#47494D").font(12.font_semiBold)
        .color("#2E3033", state: .selected).end()
    
    var model: ClubGameCommunityFenLeiModel? {
        didSet{
            guard let md = model else { return }
            cateButton.isSelected = md.isSel
            cateButton.setTitle(md.name, for: .normal)
            if md.isSel {
                cateButton.backgroundColor = .white
            }else{
                cateButton.backgroundColor = .clear
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        
        contentView.subviews{
            cateButton
        }
        
        cateButton.fillContainer()
        
        cateButton.isUserInteractionEnabled = false
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

//MARK: 分区titileView
class ClubSquareDatailHeaderView: UITableViewHeaderFooterView {
         
    private let nameLabel = c_make_ex(UILabel.self)
        .color("#2E3033").font(13.font_semiBold).end()
    
    var titleString: String? {
        didSet{
            guard let str = titleString else { return }
            nameLabel.text = str
        }
    }
    
    var isWhite: Bool = false {
        didSet{
            backgroundColor = isWhite ? UIColor.white : "#F7F8FA".toColor
            contentView.backgroundColor = isWhite ? UIColor.white : "#F7F8FA".toColor
        }
    }
    
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        backgroundColor = "#F7F8FA".toColor
        contentView.backgroundColor = "#F7F8FA".toColor
        
        subviews{
            nameLabel
        }
        
        nameLabel.leading(12.0.Scale).centerVertically()
    }
        
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    
}


class ClubSquareDatailPushView: UIView, RaeAnimationProtocol, RaeAnimationDelegate {
    
    func animationContainerViewSize() -> CGSize {
        CGSize(width: .screenWidth, height: viewH)
    }
    
    func animationContainerViewStyle() -> RaeAnimationViewStyle {
        .bottom
    }
    
    private let lineView = c_make_ex(UIView.self)
        .bgColor("#D7D8DB").corner(2.5).end()
    private let picButton = c_make_ex(UIButton.self)
        .image("SquareDetail_pushPic").end()
    private let videoButton = c_make_ex(UIButton.self)
        .image("SquareDetail_pushVideo").end()
    private var draftButton = c_make_ex(UIButton.self)
        .image("SquareDetail_pushDraft").end()
    private var viewH = 295.0
    
    var toNextVC: ((_ type: Int) -> Void)?
        
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = "#EBEBEB".toColor
        rae.corner(12.0.Scale, corners: [.layerMinXMinYCorner,.layerMaxXMinYCorner])
        
        subviews{
            lineView
            picButton
            videoButton
            draftButton
        }
        
        let h = ((CGFloat.screenWidth - 24.0.Scale) * 92.0.Scale)/351.0.Scale
        lineView.height(5.0).width(64.0).top(12).centerHorizontally()
        draftButton.trailing(24.0.Scale).height(22.0.Scale).top(20.0.Scale).width(46.0.Scale)
        picButton.leading(12.0.Scale).trailing(12.0.Scale).top(52.0.Scale).height(h)
        videoButton.leading(12.0.Scale).trailing(12.0.Scale).top(154.0.Scale).height(h)
        
        draftButton.tag = 0
        picButton.tag = 1
        videoButton.tag = 2
        
        draftButton.addTarget(self, action: #selector(pushToNextVC), for: .touchUpInside)
        picButton.addTarget(self, action: #selector(pushToNextVC), for: .touchUpInside)
        videoButton.addTarget(self, action: #selector(pushToNextVC), for: .touchUpInside)
        
        loadData()
    }
    
    private func loadData(){
        
        var isEmpty = true
        if let _ = UserDefaultsManager.getDict(forKey: .picForumPost) {
            isEmpty = false
        }
        if let _ = UserDefaultsManager.getDict(forKey: .videoForumPost) {
            isEmpty = false
        }

        draftButton.isHidden = isEmpty
        if !isEmpty {
            self.viewH = 295.0
            picButton.topConstraint?.constant = 52.0.Scale
            videoButton.topConstraint?.constant = 154.0.Scale
        }else{
            self.viewH = 260.0
            picButton.topConstraint?.constant = 30.0.Scale
            videoButton.topConstraint?.constant = 130.0.Scale
        }
    }
    
    @objc private func pushToNextVC(_ button: UIButton){
        entryAnimate.animation(dismiss: self){
            self.toNextVC?(button.tag)
        }        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

